package com.auto.netty.simple;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.concurrent.TimeUnit;

//自定义处理器类，继承Netty的HandlerAdapter(处理器规范)
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    /**
     * 读取数据事件，读取客户端发送的消息
     *
     * @param ctx 上下文对象，包含管道pipeline和通道channel
     * @param msg 客户端发送的消息
     * @throws Exception
     */
    @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
        //模拟执行逻辑耗时较长
        /*
        Thread.sleep(10 * 1000);
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello，客户端-2", CharsetUtil.UTF_8));
        */

        //解决耗时长，方法阻塞
        //方式一：用户程序自定义的普通任务
        ctx.channel().eventLoop().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(10 * 1000);
                    ctx.writeAndFlush(Unpooled.copiedBuffer("hello，客户端-2", CharsetUtil.UTF_8));
                } catch (InterruptedException e) {
                    System.out.println("出现异常：" + e.getMessage());
                }
            }
        });
        //方式二：自定义定时任务，将任务提交到scheduleTaskQueue中
        ctx.channel().eventLoop().schedule(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(10 * 1000);
                    ctx.writeAndFlush(Unpooled.copiedBuffer("hello，客户端-3", CharsetUtil.UTF_8));
                } catch (InterruptedException e) {
                    System.out.println("出现异常：" + e.getMessage());
                }
            }
        }, 5, TimeUnit.SECONDS);
        System.out.println("继续执行...");

        /*System.out.println("当前服务器线程："+Thread.currentThread().getName());
        System.out.println("server ctx = " + ctx);
        //将消息对象msg转为Netty提供的ByteBuf
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("客户端发送的消息：" + buf.toString(CharsetUtil.UTF_8));
        System.out.println("客户端地址：" + ctx.channel().remoteAddress());*/
    }

    /**
     * 数据读取完成后，给客户端响应数据
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello，客户端-1", CharsetUtil.UTF_8));
    }

    /**
     * 处理异常，一般是关闭通道
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
